$(function() {
    
    // 定位菜单
    // var url_str = $(".nav-drawer").attr('data-path');
    // var aobj = $(".nav-drawer a[href*='" + url_str + "']")[0];
    // console.log(url_str);
    // console.log(aobj);
    // // 先找具体方法，没有就找控制器
    // if (aobj != null) {
 //        if ($(aobj).parent().attr('class') == 'nav-item') {
 //            $(aobj).parent().attr('class','nav-item active');
 //        }else{
 //            $(aobj).parent().attr('class','active');
 //            $(aobj).parent().parent().parent().attr('class','nav-item nav-item-has-subnav active open');    
 //        }
 //    }else{
 //        var url_str = 'admin' + '/' + $(".nav-drawer").attr('data-controller');
 //        var aobj = $(".nav-drawer a[href*='" + url_str + "']")[0];
 //        if (aobj != null) {
 //            var class_name = $(aobj).parent().attr('class');
 //            if (class_name == null || class_name.indexOf('nav-item-has-subnav') != -1) {
 //                $(aobj).parent().parent().parent().attr('class','nav-item nav-item-has-subnav active open');    
 //            }else{
 //                $(aobj).parent().attr('class','nav-item active');    
 //            }
 //        }
 //    }
    // 时间插件
    $(".js-datepicker-time").datetimepicker({
        format: "yyyy-mm-dd hh:ii",
        // showMeridian: true,
        autoclose: true,
        todayBtn: true,
        language: 'zh-CN'
    });

    // 批量删除
    $(".more_delete_btn").on('click',function(){
        var ids = [];
        $(".item_check:checked").each(function(){
            ids.push($(this).val());
        });
        if (ids.length == 0) {
            alert('请勾选选项');
            return false;
        }
        if (!confirm('确定批量删除？')) {
            return false;
        }

        var url = $(this).data('url');
        url = url + '?ids='+ids.join(',');
        window.location.href = url;
    });

    // select2
    if ($(".js-select2").length > 0) {
        $(".js-select2").select2({width: '100%'});
    }

    // 生成单个上传控件
    $(".uploader_btn").each(function(){
        var btn = $(this);
        var thumbnailWidth = thumbnailHeight = 60;
        if (upload_type == 'index') {
            var upload_api_server = '/index.php/index/base/upload';
        }else{
            var upload_api_server = '/index.php/admin/base/upload';
        }
        var uploader = WebUploader.create({
            auto: true,
            // 不压缩image
            resize: false,
            // swf文件路径
            swf: static_path+'/common/webuploader/Uploader.swf',
            // 文件接收服务端。
            server: upload_api_server,
            // 选择文件的按钮。可选。
            pick: '#' + $(btn).attr('id')
        });


        // 当有文件添加进来的时候
        uploader.on( 'fileQueued', function( file ) {
            // 创建缩略图
            uploader.makeThumb( file, function( error, src ) {
                if ( error ) {
                    $(btn).next('span').html('不能预览'); return;
                }
            }, thumbnailWidth, thumbnailHeight );
        });
        uploader.on( 'uploadSuccess', function( file , response ) {
            if (response.code == 2000) {
                var img_url = response.data.savename;
                $(btn).nextAll('input').val(img_url);
                $(btn).next('span').html(response.msg);
                console.log($(btn).nextAll('img'))
                $(btn).nextAll('img').attr( 'src', upload_path+'/'+img_url );
            }else{
                $(btn).next('span').html('上传失败：'+response.msg);
            }
        });
        uploader.on( 'uploadError', function( file , response ) {
            $(btn).next('span').html(response.msg);
        });
    });

    // 生成多个上传控件
    $(".uploader_btns").each(function(){
        var btn = $(this);
        var thumbnailWidth = thumbnailHeight = 60;
        if (upload_type == 'index') {
            var upload_api_server = '/index.php/index/base/upload';
        }else{
            var upload_api_server = '/index.php/admin/base/upload';
        }
        var uploader = WebUploader.create({
            auto: true,
            height:100,
            // 不压缩image
            resize: false,
            // swf文件路径
            swf: static_path+'/common/webuploader/Uploader.swf',
            // 文件接收服务端。
            server: upload_api_server,
            // 选择文件的按钮。可选。
            pick: '#' + $(btn).attr('id')
        });

        // 当有文件添加进来的时候
        uploader.on( 'fileQueued', function( file ) {
            // 创建缩略图
            uploader.makeThumb( file, function( error, src ) {
                if ( error ) {
                    $(btn).next('span').html('不能预览'); return;
                }
            }, thumbnailWidth, thumbnailHeight );
        });
        uploader.on( 'uploadSuccess', function( file , response ) {
            if (response.code == 2000) {
                var img_url = response.data.savename;
                var field = $(btn).attr('id');
                var str = '<div class="item">'+
                                '<p><img src="'+(upload_path+'/'+img_url)+'" class="cch_thumbnail"></p>'+
                                '<input type="hidden" name="'+field+'[]" value="'+img_url+'" />'+
                                '<button type="button" class="btn btn-xs btn-danger" onclick="uploader_del(this)">删除</button>'+
                            '</div>';
                $(btn).parent().next('.uploader_more_div').append( str );
            }
        });
        uploader.on( 'uploadError', function( file , response ) {
            $(btn).next('span').html(response.msg);
        });
    });

    // 生成百度编辑器
    $(".ueditor").each(function(){
        var ue = UE.getEditor($(this).attr('id'),{
            initialFrameWidth :'100%',
            'initialFrameHeight':320
        });
    });

    // 丢失图片，默认图
    $(".cch_thumbnail").on('error',function(){
        $(this).attr('src',static_path + '/common/images/no_img.png');
    });

    // 删除按钮
    $(".delete_btn").on('click',function(){
        return confirm('确定删除？');
    });

    // 复选框 全选 / 取消全选
    $(".all_check").on('click',function(){
        if ($(this).prop("checked")) {
            $(".item_check").prop("checked",true);
        }else{
            $(".item_check").removeAttr("checked");
        }
    });

    // 导出按钮
    $('.export_btn').on('click',function(){
        var action = $(this).attr('data-action');
        if (action == null || action == '') {
            action = 'export';
        }
        $(this).parents().prev('form').attr('action',action);
        $(this).parents().prev('form').submit();
        setTimeout(function(){
            $(this).parents().prev('form').attr('action','index');
        },1000);

        var l = $('body').lyearloading({
            opacity: 0.5,
            spinnerSize: 'lg',
            spinnerText: '导出中...完成后手动刷新页面',
            textColorClass: 'text-info',
            spinnerColorClass: 'text-info'
        });
    });

    $('.search_btn').on('click',function(){
        console.log($(this).parents().parents('form'));
        $(this).parents().prev('form').submit();
    });
    
});

// 多图上传 - 删除item
function uploader_del(btn){
    $(btn).parent().remove();
}

$('.tags-btn').on('click',function(){
    if ($(this).attr('class').indexOf('btn-success') == -1) {
        // $(this).addClass('btn-success');
        $( '.js-tags-input' ).addTag($(this).html());    
    }else{
        // $(this).removeClass('btn-success');
        $( '.js-tags-input' ).removeTag($(this).html());   
    }
});

function onAddTag(params){
    $('.tags-btn').each(function(){
        if ($(this).html() == params) {
            $(this).addClass('btn-success');
        }
    });
}

function onRemoveTag(params){
    $('.tags-btn').each(function(){
        if ($(this).html() == params) {
            $(this).removeClass('btn-success');
        }
    });
}

// 单图删除
function uploader_one_del(btn){
    $(btn).prevAll('img').attr('src','');
    $(btn).prevAll('span').html('');
}